LeetCode JS Easy 2704. To Be Or Not To Be


Posted by Lucy on 2023-06-10

這是30 Days of JavaScript中的題型
Write a function expect that helps developers test their code. It should take in any value val and return an object with the following two functions.

toBe(val) accepts another value and returns true if the two values === each other. If they are not equal, it should throw an error "Not Equal".
notToBe(val) accepts another value and returns true if the two values !== each other. If they are equal, it should throw an error "Equal".
最常見寫法應該就兩個function

var expect = function(val) {
    const toBe=(eqalVal)=>{if(val===eqalVal)return true
                throw new Error("Not Equal")
    }    
    const notToBe=(eqalVal)=>{if(val!==eqalVal)return true
                throw new Error("Equal")
    }
      return {
          toBe:toBe,
          notToBe:notToBe,
      }
};

不過不知道為什麼我就很想寫共用function,下面這段是第一次寫的

var expect = function(val) {
    const fn=(eqalVal,isToBe)=>{
            const isEqal=val===eqalVal
            if(isToBe){
                if(isEqal)return true
                throw new Error("Not Equal")
            }else{
                if(isEqal)throw new Error("Equal")
                return true
            }
        }
      return {
          toBe:(eqalVal)=>fn(eqalVal,true),
          notToBe:(eqalVal)=>fn(eqalVal,false),
      }
};

#leetcode Js







Related Posts

Introducing Asymptotic Measures

Introducing Asymptotic Measures

變數命名的善意

變數命名的善意

超讚 Deep Learning on 3D object detection 相關教學影片彙整

超讚 Deep Learning on 3D object detection 相關教學影片彙整


Comments